layui.config({
    dir: '/eshop/static/layui/'
})
var table1,m;
//JavaScript代码区域
layui.use('table', function () {
    var $ = layui.$//通过layui获取到jquery
    var table = layui.table,form = layui.form, layer = layui.layer;
    //渲染数据表格
    table1 = table.render( {
        elem: '#demo'
        , height: 500
        , url: '/eshop/Users.do?m=findAll' //数据接口
        , page: true //开启分页
        , parseData: function (data) {
            console.log(data);
            /*return {
                "code": 0,
                "msg": "",
                "count": data.length,
                "data": data
            }*/
        }
        ,done:function (res) {
            console.log(res);
        }
        ,request: {
            pageName: 'current' //页码的参数名称，默认：page
            ,limitName: 'limit' //每页数据量的参数名，默认：limit
        }
        , cols: [[ //表头
            {field: 'id', title: 'ID', }
            , {field: 'username', title: '用户名'}
            , {field: 'password', title: '密码'}
            , {field: 'imgUrl', title: '头像',align: 'center',templet:function (d) {
                    return '<div><img src="/eshop/Img.do?m=showImg&name='+d.imgUrl+'" style="width: 50px;height: 50px;border-radius: 50%;" ></div>'
                }}
            , {
                field: 'type', title: '类型', templet: function (d) {
                    return d.type == "0" ? "后台用户" : "前台用户";
                }
            }
            , {
                field: 'id', title: '操作', templet: function (d) {
                    return '<button str="'+d.id+'" onclick="update(this)" class="layui-btn layui-btn-sm"><span class="layui-icon layui-icon-edit"></span>修改</button>' +
                        '<button str="'+d.id+'" onclick="deleteUser(this)" class="layui-btn layui-btn-sm  layui-btn-danger"><span class="layui-icon layui-icon-delete"></span>删除</button>'
                }
            }
        ]]
    });
    //添加点击方法
    $("#add").click(function () {
        m='add';
        $("#username").bind("blur",function () {
            repeatUser($(this).val())
        })
        layer.open({
            type: 1,
            title: "添加用户",
            maxmin: false,
            shadeClose: true,
            area: ['400px', '350px'],
            content: $("#model")
            , success: function (layero) {
                //把内容放到遮罩层里
                var mask = $(".layui-layer-shade");
                mask.appendTo(layero.parent());
            }
        });
    });

    //提交添加和修改方法
    form.on('submit(formDemo)', function(obj){
            if(!eval(repeatUser($("#username").val()))){
                return false;
            }
        $.ajax({
            url:'/eshop/Users.do?m='+m,
            type:'post',
            data:obj.field,
            dataType:'json',
            success:function (data){
                layer.msg(JSON.stringify(data))
                if (data=='成功'){
                    layer.closeAll('page');
                    table1.reload('demo', {});
                }
            }
        })
        return false;
    });


    $("#username").bind("blur",function () {
        repeatUser($(this).val())
    })
});
//删除方法
function deleteUser(d) {
    layer.confirm('您确定要删除这条数据吗？', {
        btn: ['确定','取消'] //按钮
    }, function()
    {
        layer.closeAll('dialog');
        $.ajax({
            type: 'get',
            url: '/eshop/Users.do?m=delete',
            data: {id: $(d).attr('str')},
            success: function (data) {
                if (data == '删除成功') {
                    layer.closeAll('page');
                    table1.reload('demo', {});
                }
            }
        })
    });

   // layer.closeAll('dialog');  //点击确定关闭提示框

}

//修改方法
function update(e) {
    m='update'
    $.ajax({
        url:"/eshop//Users.do?m=findByID",
        type:'get',
        data:{id:$(e).attr('str')},
        dataType: "json",
        success:function (data) {
            $("#username").val(data.username)
            $("#password").val(data.password)
            $("#userid").val(data.id)
            $("#img").attr("src","/eshop/Img.do?m=showImg&name="+data.imgUrl);
            $("#imgUrl").val(data.imgUrl)
            var select1 = 'dd[lay-value=' + data.type + ']';
            $('#type').siblings("div.layui-form-select").find('dl').find(select1).click();
        }
    })
    layer.open({
        type: 1,
        title: "修改用户",
        maxmin: false,
        shadeClose: true,
        area: ['400px', '350px'],
        content: $("#model")
        , success: function (layero) {
            //把内容放到遮罩层里
            var mask = $(".layui-layer-shade");
            mask.appendTo(layero.parent());
        }
    });


}

//查看是否有该用户
function repeatUser(username) {
    let msg;
    $.ajax({
        async: false,//同步
        url:"/eshop/Users.do?m=findUsername&username="+username,
        type:"get",
        dataType:"json",
        success:function (data) {
            layer.msg(JSON.stringify(data))
            if(data=='用户名重复')
                msg ='false'
            else
                msg = 'true'
        }
    })
    return msg
}

//图片上传方法
layui.use('upload', function(){
    var upload = layui.upload;

    //执行实例
    var uploadInst = upload.render({
        elem: '#file' //绑定元素
        ,url: '/eshop/Img.do?m=uploadImg' //上传接口
        ,done: function(res){
            //上传完毕回调
            $("#img").attr("src","/eshop/Img.do?m=showImg&name="+res.data.src);
            $("#imgUrl").val(res.data.src)
        }
        ,error: function(){
            //请求异常回调
            console.log("error")
        }
    });
});
